<template>
  <div class="bgimage">
    <div class="container" v-show="login">
      <el-form :model="form" :rules="rules" ref="formRef">
        <h1>登录</h1>
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="输入用户名"
            size="large"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><Avatar /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            show-password
            v-model="form.password"
            placeholder="输入密码"
            size="large"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <div style="display: flex; margin-bottom: 20px">
          <el-input v-model="yanzheng" placeholder="输入验证码" size="large">
          </el-input>
          <div style="width: 10px"></div>
          <div @click="refreshCode">
            <SIdentify :identifyCode="identifyCode" />
          </div>
        </div>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" size="large"
            >确认登录</el-button
          >
          <!-- <p style="width: 100%">
            <el-link
              type="primary"
              style="text-align: end"
              @click="login = false"
              >注册</el-link
            >
          </p> -->
        </el-form-item>
      </el-form>
    </div>
    <div class="container" v-show="!login">
      <el-form status-icon :model="formRes" :rules="rulesRes" ref="formResr">
        <h1>注册</h1>
        <el-form-item prop="name">
          <el-input
            size="large"
            maxlength="6"
            show-word-limit
            v-model="formRes.name"
            placeholder="输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="psd">
          <el-input
            size="large"
            type="password"
            show-password
            v-model="formRes.psd"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="surepsd">
          <el-input
            size="large"
            v-model="formRes.surepsd"
            placeholder="请确认密码"
            type="password"
            show-password
            @blur="confirmFunc"
          ></el-input>
        </el-form-item>
        <el-form-item type="text" prop="truname">
          <el-input
            v-model="formRes.truname"
            placeholder="用户真实姓名"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            maxlength="11"
            show-word-limit
            v-model="formRes.phone"
            oninput="value=value.replace(/[^\d]/g,'')"
            placeholder="联系方式"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onRegister" size="large"
            >确认注册</el-button
          >
        </el-form-item>
        <p style="width: 100%">
          <el-link type="primary" style="text-align: end" @click="login = true"
            >登录</el-link
          >
        </p>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import SIdentify from '@/components/Sidentify.vue'

import { reactive, ref, onMounted } from 'vue'
import userApi from '@/apis/user.js'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
// 引入pinia
// import { useUserStore } from '@/stores/user.js'
import router from '../router'
const login = ref(true)
/* ------------------验证码----------------- */
// 图形验证码
let identifyCodes = '1234567890'
let identifyCode = ref('3212')
const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min)
}
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)]
  }
}
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes, 4)
}
onMounted(() => {
  identifyCode.value = ''
  makeCode(identifyCodes, 4)
})

const yanzheng = ref('') // 自己输入的验证码
/* ------------------------------------- */

// 定义登录表单
// do not use same name with ref
const { user } = useUserStore()
const form = reactive({
  username: '',
  password: '',
})
// 定义登录的校验规则
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 2, max: 5, message: '用户名长度在2~5个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 10, message: '用户名长度在6~10个字符', trigger: 'blur' },
  ],
}
// 定义注册表单校验
const formRes = reactive({
  name: '',
  psd: '',
  surepsd: '',
  truname: '',
  phone: '',
})
// const closable = ref(true)
// 定义用户联系方式的输入内容格式
// const input = ref('')
// 定义注册的表单校验规则
const rulesRes = {
  psd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 10, message: '密码长度在6~10个字符', trigger: 'blur' },
  ],
  truname: [
    { required: true, message: '真实姓名不能为空', trigger: 'blur' },
    { min: 2, max: 5, message: '用户名长度在2~5个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '联系方式不能为空', trigger: 'blur' },
    { min: 6, max: 11, message: '用户名长度在6~11个字符', trigger: 'blur' },
  ],
}
// 定义响应式数据
const formResr = ref(null)
// 确认密码校验
const confirmFunc = () => {
  if (formRes.surepsd !== formRes.psd) ElMessage.error('密码与确认密码不一致.')
}
// 注册请求
const onRegister = () => {
  console.log('注册', formRes)
  formResr.value.validate((valid) => {
    // console.log(valid)
    if (!valid) {
      return false
    }
    // console.log('验证通过')
    userApi
      .addOne({
        user_name: formRes.name,
        user_password: formRes.psd,
        user_truname: formRes.truname,
        user_phone: formRes.phone,
      })
      .then((res) => {
        // console.log(res)
        if (res.code == '0') {
          // alert(res.message)
          // closable.value = false
          formRes.name = ''
          formRes.psd = ''
          formRes.surepsd = ''
          formRes.truname = ''
          formRes.phone = ''
          ElMessage.success('注册成功')
          login.value = true
        }
      })
      .catch((err) => {
        console.log(err)
      })
  })
}
// 登录触发表单校验
const formRef = ref(null)
// 登录触发表事件
const onSubmit = () => {
  if (identifyCode.value != yanzheng.value) {
    ElMessage.error('验证码错误，请重新输入')
    return false
  }
  // if (form.username == 'user_name' && form.password == 'user_password')
  // console.log(formRef.value)
  formRef.value.validate((valid) => {
    // console.log(valid)
    if (!valid) {
      return false
    }
    // console.log('验证通过')
    userApi
      .addOld({ user_name: form.username, user_password: form.password })
      .then((res) => {
        console.log(res, 'zzz')
        if (res.code == '0') {
          // alert(res.message)
          // console.log(res.result.token)
          console.log(res.result, '状态')
          const token = res.result.token
          // console.log(token)
          const userId = res.result.id
          localStorage.setItem('token', token)
          // console.log(token)
          localStorage.setItem('userId', userId)
          ElMessage.success('登录成功')
          router.push('/home')
          // console.log(userId)
          // console.log(token)
          // console.log(localStorage.token)

          // localStorage.removeItem('token', res.result.token)
        } else {
          ElMessage.error('请输入正确的用户名和密码')
        }
      })
      .catch((err) => {
        console.log(err)
      })
  })
}
// 注册pinia
// const store = useUserStore()
</script>

<style scoped>
.container {
  display: flex;
  height: 100%;
  align-items: center;
}
.container h1 {
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  color: #444;
  margin-bottom: 20px;
}
.el-form {
  background: rgba(255, 255, 255, 0.7);
  box-shadow: 0 0 10px 10px rgba(255, 255, 255, 0.9);
  width: 350px;
  margin: 0 auto;
  padding: 20px;
  border-radius: 10px;
}
.bgimage {
  background-image: url(@/assets/images/bg.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  width: 100%;
  height: 100vh;
}
.container button {
  /* background-color: rgba(165, 234, 250, 0.2); */
  width: 100% !important;
}
</style>
